package com.stox.client.http;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import com.stox.client.CountryClient;
import com.stox.client.ExchangeClient;
import com.stox.client.ScripClient;
import com.stox.dto.Country;
import com.stox.dto.Exchange;
import com.stox.dto.Scrip;
import com.stox.dto.web.Response;

@Component
public class ScripHttpClient extends AbstractHttpClient implements ScripClient {

	@Autowired
	private CacheManager cacheManager;
	
	@Autowired
	private CountryClient countryClient;
	
	@Autowired
	private ExchangeClient exchangeClient;
	
	@Override
	@Cacheable("com.stox.dto.Scrip")
	public List<Scrip> findByExchangeId(Long exchangeId) {
		return extract(getRestTemplate().exchange(getRootUrl()+"/scrips?exchangeId="+exchangeId, HttpMethod.GET, null, new ParameterizedTypeReference<Response<List<Scrip>>>(){}));
	}

	@Override
	@SuppressWarnings("unchecked")
	@Cacheable("com.stox.dto.Scrip")
	public Scrip findOne(Long id){
		
		Cache cache = cacheManager.getCache("com.stox.dto.Scrip");
		if(null != cache){
			for(Country country : countryClient.findAll()){
				for(Exchange exchange : exchangeClient.findByCountryCode(country.getId())){
					ValueWrapper wrapper = cache.get(exchange.getId());
					if(null != wrapper && null != wrapper.get() && wrapper.get() instanceof List){
						List<Scrip> scrips = (List<Scrip>)wrapper.get();
						for(Scrip scrip : scrips){
							if(scrip.getId().equals(id)){
								return scrip;
							}
						}
					}
				}
			}
		}
		
		return extract(getRestTemplate().exchange(getRootUrl() + "/scrips/" + id, HttpMethod.GET, null, new ParameterizedTypeReference<Response<Scrip>>(){}));
	}
	
}
